package com.iqiju.guagua.photo.wx.mini.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iqiju.guagua.photo.wx.mini.common.Results;
import com.iqiju.guagua.photo.wx.mini.mapper.WxPhotoMapper;
import com.iqiju.guagua.photo.wx.mini.model.*;
import com.iqiju.guagua.photo.wx.mini.vo.TemplateVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class WxPhotoService extends ServiceImpl<WxPhotoMapper, WxPhoto> {

    @Autowired
    private WxMiniAppConfigService wxMiniAppConfigService;

    @Autowired
    private WxMiniAppService wxMiniAppService;

    @Autowired
    private WxUserPhotoService wxUserPhotoService;

    @Autowired
    private WxMiniUserService wxMiniUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    public Results<TemplateVO> userPhotoTemplate(String userTemplateId) {
        if (userTemplateId==null || userTemplateId.trim().length()<=0){
            log.error("参数 userTemplateId 为空！");
            return Results.paramError("参数 userTemplateId 不能为空");
        }

        List<WxUserPhoto> wxUserPhotos = wxUserPhotoService.selectListByUserTemplateId(userTemplateId);
        if (wxUserPhotos.isEmpty()){
            log.error("参数 userTemplateId 不合法  {}",userTemplateId);
            return Results.paramError("参数 userTemplateId 不合法");
        }



        Long wxMiniAppId = wxUserPhotos.get(0).getWxMiniAppId();
        Integer no = wxUserPhotos.get(0).getNo();

        Results<TemplateVO> templateResult = template(String.valueOf(wxMiniAppId), String.valueOf(no));

        if (templateResult.getState()!=0){
            log.error("相册数据有误  userTemplateId={}",userTemplateId);
            return Results.error("相册数据有误！userTemplateId="+userTemplateId);
        }

        templateResult.getContent().setNo(String.valueOf(no));
        templateResult.getContent().getMateImgUrls().clear();




        long userId = 0;
        for (WxUserPhoto wxUserPhoto : wxUserPhotos) {
            userId = wxUserPhoto.getUserId();
            templateResult.getContent().getMateImgUrls().add(wxUserPhoto.getUrl());
        }
        templateResult.getContent().setNickName("我");
        if (userId>0){
            WxMiniUser wxMiniUser = wxMiniUserService.selectById(userId);
            if (wxMiniUser!=null){
                if (wxMiniUser.getNickName()!=null&&wxMiniUser.getNickName().trim().length()>0){
                    templateResult.getContent().setNickName(wxMiniUser.getNickName());
                    log.info("有用户昵称");
                }else{
                    log.warn("没有用户昵称  userTemplateId={}", userTemplateId);
                }
                if (wxMiniUser.getAvatarUrl()!=null&&wxMiniUser.getAvatarUrl().trim().length()>0){
                    templateResult.getContent().setHeadUrl(wxMiniUser.getAvatarUrl());
                    log.info("有用户头像");
                }else{
                    log.warn("没有用户头像  userTemplateId={}", userTemplateId);
                }
            }
        }else{
            log.error("没有获取到当前用户的id   userTemplateId={}", userTemplateId);
        }



        return templateResult;
    }

    public Results<TemplateVO> template(String wxMiniAppId, String num) {
        if (wxMiniAppId==null || wxMiniAppId.trim().length()<=0){
            log.error("参数 wxMiniAppId 为空！");
            return Results.paramError("参数 wxMiniAppId 不能为空");
        }
        if (num==null || num.trim().length()<=0){
            log.error("参数 num 为空！");
            return Results.paramError("参数 num 不能为空");
        }

        if ("undefined".equals(num)){
            log.error("参数 num 不合法！");
            return Results.paramError("参数 num 不合法");
        }

        WxMiniApp wxMiniApp = wxMiniAppService.selectById(Long.parseLong(wxMiniAppId));
        if (wxMiniApp == null){
            log.error("小程序id "+wxMiniAppId+" 不存在！");
            return Results.paramError("小程序id "+wxMiniAppId+" 不存在");
        }

        String templateValue = stringRedisTemplate.opsForValue().get(getSystemTemplateKey(wxMiniAppId, num));
        if (templateValue!=null&&templateValue.trim().length()>0){
            TemplateVO templateValueObject = JSON.parseObject(templateValue,TemplateVO.class);
            log.info("从redis中查询到模板  wxMiniAppId={}   no={}", wxMiniAppId,num);
            templateValueObject.getWords().set(0,getPhotoTimeStr(Integer.parseInt(num)));
            return new Results(Results.SUCCESS_CODE,Results.SUCCESS_MSG,templateValueObject);
        }
        log.warn("未从redis中查询到模板  wxMiniAppId={}   no={}", wxMiniAppId,num);


        QueryWrapper<WxPhoto> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_mini_app_id",wxMiniAppId);
        wrapper.eq("no",num);
        List<WxPhoto> wxPhotos = list(wrapper);
        if (wxPhotos.isEmpty()){
            return Results.paramError("未定义动效 "+num);
        }

        TemplateVO templateVO = new TemplateVO();
        templateVO.setNo(num);
        templateVO.setName(wxPhotos.get(0).getName());
        templateVO.setMoveType(wxPhotos.get(0).getMoveType());
        for (WxPhoto wxPhoto : wxPhotos) {
            if (1==wxPhoto.getType()){
                templateVO.setBackImgUrl(wxPhoto.getUrl());
            }else if (2==wxPhoto.getType()){
                templateVO.setFrontImgUrl(wxPhoto.getUrl());
            }else if (3==wxPhoto.getType()){
                templateVO.getMoveImgUrls().add(wxPhoto.getUrl());
            }else if (4==wxPhoto.getType()){
                templateVO.getMateImgUrls().add(wxPhoto.getUrl());
            }else if (5==wxPhoto.getType()){
                templateVO.setHeadUrl(wxPhoto.getUrl());
            }else if (6==wxPhoto.getType()){
                templateVO.setMusic(wxPhoto.getUrl());
            }
        }
        templateVO.getWords().add(getPhotoTimeStr(Integer.parseInt(num)));

        String typeKeyValue = wxMiniAppConfigService.selectByTypeAndKey(Long.valueOf(wxMiniAppId), "TEMPLATE_WORDS_CONFIG", num);
        if (typeKeyValue!=null&&typeKeyValue.trim().length()>0){
            String[] two = typeKeyValue.split("---");
            String[] oneWords = two[0].replace("_", " ").split(",");
            Collections.addAll(templateVO.getWords(),oneWords);
            if (two.length>1){
                String[] twoWords = two[1].replace("_", " ").split(",");
                Collections.addAll(templateVO.getSecondWords(),twoWords);
            }
        }

        String shareWords = wxMiniAppConfigService.selectByTypeAndKey(Long.valueOf(wxMiniAppId), "TEMPLATE_SHARE_WORDS_CONFIG", num);
        templateVO.setShareWords(shareWords);

        String templateToWxEnable = wxMiniAppConfigService.selectByTypeAndKey(Long.valueOf(wxMiniAppId), "TEMPLATE_TO_WX_MINI", "ENABLE");
        if ("1".equals(templateToWxEnable)){
            String templateToWxUrl = wxMiniAppConfigService.selectByTypeAndKey(Long.valueOf(wxMiniAppId), "TEMPLATE_TO_WX_MINI", "URL");
            if (templateToWxUrl!=null&&templateToWxUrl.trim().length()>0){
                templateVO.getTemplateUrlVO().setUrl(templateToWxUrl);
                String templateToWxOpenid = wxMiniAppConfigService.selectByTypeAndKey(Long.valueOf(wxMiniAppId), "TEMPLATE_TO_WX_MINI", "OPENID");
                if (templateToWxOpenid!=null&&templateToWxOpenid.trim().length()>0){
                    templateVO.getTemplateUrlVO().setOpenid(templateToWxOpenid);
                    templateVO.getTemplateUrlVO().setEnable(1);
                }
            }
        }


        stringRedisTemplate.opsForValue().set(getSystemTemplateKey(wxMiniAppId,num),JSON.toJSONString(templateVO),30,TimeUnit.DAYS);

        return new Results<>(Results.SUCCESS_CODE,Results.SUCCESS_MSG,templateVO);
    }







    public String getPhotoTimeStr(int no){
        StringBuilder sb = new StringBuilder();
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        if (0==(no%2)){
            if (hour>=18||hour<4){
                sb.append("晚上好");
            }else if(hour>=4&&hour<8){
                sb.append("早上好");
            }else if(hour>=8&&hour<12){
                sb.append("上午好");
            }else if(hour>=12&&hour<18){
                sb.append("下午好");
            }
        }else{
            sb.append("今天是").append(now.getMonth().getValue()).append("月").append(now.getDayOfMonth()).append("日 ");
            int dayOfWeek = now.getDayOfWeek().getValue();
            switch (dayOfWeek){
                case 1: sb.append("星期一"); break;
                case 2: sb.append("星期二"); break;
                case 3: sb.append("星期三"); break;
                case 4: sb.append("星期四"); break;
                case 5: sb.append("星期五"); break;
                case 6: sb.append("星期六"); break;
                case 7: sb.append("星期日"); break;
            }
        }
        return sb.toString();
    }


    public Results<List<Integer>> nums(String wxMiniAppId) {

        if (wxMiniAppId==null || wxMiniAppId.trim().length()<=0){
            log.error("参数 wxMiniAppId 为空！");
            return Results.paramError("参数 wxMiniAppId 不能为空");
        }
        Long miniId = null;
        try {
            miniId = Long.parseLong(wxMiniAppId);
        } catch (NumberFormatException e) {
            log.error("wxMiniAppId=[{}] 转换为long出现异常", wxMiniAppId);
            log.error(e.getMessage(), e);
            return Results.error("wxMiniAppId=["+wxMiniAppId+"] 转换为long出现异常");
        }

        String numsOrder = wxMiniAppConfigService.selectByTypeAndKey(miniId, "TEMPLATE_PHOTO_CONFIG", "ORDER_NUMS");
        if (numsOrder==null||numsOrder.trim().length()<=0){
            return Results.error("wxMiniAppId=["+wxMiniAppId+"]  模板顺序配置为空");
        }
        String[] nums = numsOrder.split(",");
        return Results.success(nums);
    }


    private String getSystemTemplateKey(String wxMiniAppId, String no){
        return "GUAGUA_PHOTO_TEMPLATE_" + wxMiniAppId + "_" + no;
    }
}
